---
layout: post
title: An Encrypt and Dectrypt tool with sjcl.js
author: DeerRIDER
category: Sample
date: 2019-4-16
---

<!-- aes encrypt and decrypt method -->
<script
  src="{{ site.url }}{{ site.baseurl }}{{ site.assets_path }}/js/sjcl.js"
  async
></script>

<div class="div_token">
  <table>
    <thead>
      <th colspan="3">
        Password is required in both encryption and decryption
      </th>
    </thead>
    <tbody>
      <tr>
        <td>Password</td>
        <td>
          <textarea
            class="access_token"
            rows="1"
            cols="50"
            id="pwd"
            style="resize: vertical;"
          ></textarea>
        </td>
        <td></td>
      </tr>
      <tr>
        <td>
          Message
        </td>
        <td>
          <textarea
            class="access_token"
            rows="5"
            cols="50"
            id="msg"
            style="resize: vertical;"
          ></textarea>
        </td>
        <td><button class="encrypt" onclick="encrypt()">Encrypt</button></td>
      </tr>
      <tr>
        <td>Ciphertext</td>
        <td>
          <textarea
            class="access_token"
            rows="5"
            cols="50"
            id="ct"
            style="resize: vertical;"
          ></textarea>
        </td>
        <td><button class="encrypt" onclick="decrypt()">Decrypt</button></td>
      </tr>
      <tr>
        <td>Minimized</td>
        <td>
          <textarea
            class="access_token"
            rows="5"
            cols="50"
            id="min_text"
            style="resize: vertical;"
          ></textarea>
        </td>
        <td></td>
      </tr>
    </tbody>
  </table>
</div>
<script>
  function encrypt() {
    var pwd = document.getElementById("pwd").value;
    var msg = document.getElementById("msg").value;
    var ct =  sjcl.json.encrypt(pwd, msg,{salt: ""});
    var ct_obj = JSON.parse(ct);
    document.getElementById("ct").value = ct;
    document.getElementById("msg").value = "";
    document.getElementById("min_text").value = (ct_obj.iv.substring(0,22) + ct_obj.ct);
  }
  function decrypt() {
    var pwd = document.getElementById("pwd").value;
    var ct = document.getElementById("ct").value;
    document.getElementById("msg").value = sjcl.json.decrypt(pwd, ct);
    document.getElementById("ct").value = "";
    document.getElementById("min_text").value = "";
  }
</script>
